package com.base.myproject.client.busi.system;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.JDBCModelData;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.listener.HeardBeatEvent;
import com.base.myproject.client.listener.HeardBeatListener;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.tools.SendServlet;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseHeartBeat;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.DataField;
import com.extjs.gxt.ui.client.data.HttpProxy;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.LoadEvent;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.data.XmlReader;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FieldEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.LoadListener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.GroupingStore;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.CheckColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.grid.GridGroupRenderer;
import com.extjs.gxt.ui.client.widget.grid.GroupColumnData;
import com.extjs.gxt.ui.client.widget.grid.GroupingView;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;

public class TaskClient extends LayoutContainer implements HeardBeatListener {
	BaseStore<JDBCModelData>  store =null;
	
	GroupingStore<JDBCModelData>  groupstore =null;
	boolean isediting=false; // 如果行被选中说明处于编辑状态
	boolean isneedreload = false;//是否需要重新加载
	BaseGrid grid =null;
	FormBinding formBindings ;
	FormBinding leftformBindings ;
	FormBinding rightformBindings ;
	 FormPanel toppanel ;
	 FormPanel leftpanel;
	 FormPanel rightpanel;
	 Grid groupgrid=null;
	 BasePagingLoader loder;
	public TaskClient()
	{
		init();
	}

	@SuppressWarnings("unchecked")
	private void init() {
		
		//getStore();
		getgroupstore();
	
		setLayout(new BorderLayout());
		BorderLayoutData weatData = new BorderLayoutData(LayoutRegion.WEST, 150);  
		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER, 10);  
		//grid = getBaseGrid();
		groupgrid= getGroupGrid();
		VerticalPanel vp = new VerticalPanel();
		vp.setAutoWidth(true);
		vp.setAutoHeight(true);
		FieldSet fs = CreateForm();
		vp.add(groupgrid);

		//vp.add(grid);
		vp.add(fs);
		this.add(vp,centerData);
		this.add(CreateLeftPanel(),weatData);
		this.setSize(900, 800);
		
		 formBindings = new FormBinding(toppanel, true);  
		 leftformBindings = new FormBinding(leftpanel, true);  
		 rightformBindings = new FormBinding(rightpanel, true);  
	//	this.setAutoHeight(true);
	//	this.addHeardBeatListener("zgw",BaseHeartBeat.getinstance());
		BaseHeartBeat bhb = BaseHeartBeat.getinstance();
		bhb.addHeardBeatListener("reload", this);
		
		groupgrid.getSelectionModel().addSelectionChangedListener(new SelectionChangedListener(){

			@Override
			public void selectionChanged(SelectionChangedEvent se) {
				
				
				if(groupgrid.getSelectionModel().getSelectedItems().size()<=0)
				{
					isediting = false;
					if(isneedreload)
					{
						//store.reload();
						loder.load();
						isneedreload = false;
					}
				}
				else
				{
					isediting = true;
				}
			}

		});
		
	}
	private void getgroupstore()
	{
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");

		type.addField("icode");
		type.addField("taskname");
		type.addField("bcode");
		type.addField("predate");
		type.addField("modifydatebak");
		type.addField("fromaddr");
		type.addField("toaddr");
		type.addField("subject");
		type.addField("status");

		
		StoreInfo info = new StoreInfo();

		info.setTablename("task");
		info.setSql("select * from task");
		 loder = getBaseLoader(type,info);
		 groupstore = new GroupingStore<JDBCModelData>(loder);  
		 loder.load();
		 groupstore.groupBy("modifydatebak");  
		 loder.addLoadListener(new LoadListener(){
			 public void loaderLoad(LoadEvent e){
				 System.out.println("group ............");
			 }
		 });
		// groupstore.addStoreListener(new StoreListener<JDBCModelData>(){});
		 
		 
	}
	public  BasePagingLoader< PagingLoadResult<JDBCModelData>> getBaseLoader(final ModelType type,StoreInfo storeinfo) {
		Date date = new Date();
		RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,
				URL.encode("TaskServlet?Action=Loaddata"));
		builder.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");  

		builder.setCallback(new RequestCallback(){

			@Override
			public void onError(Request request, Throwable exception) {
				// TODO Auto-generated method stub
				System.out.println("error.....");
			}

			@Override
			public void onResponseReceived(Request request, Response response) {
				// 
				
			
			}});
		HttpProxy proxy = new HttpProxy(builder);

		// need a loader, proxy, and reader
		XmlReader reader = new XmlReader( type)
		{
			
			protected ListLoadResult newLoadResult(Object loadConfig, List models) { 
					PagingLoadConfig pagingConfig = (PagingLoadConfig) loadConfig; 
					PagingLoadResult <ModelData> result = new BasePagingLoadResult<ModelData>(models, 
					pagingConfig.getOffset(), pagingConfig.getLimit()); 
					 
					return result; 
					} 
			@Override 
			 public ListLoadResult read(Object loadConfig, Object data) {
				    Document doc = XMLParser.parse((String) data);

				    NodeList list = doc.getElementsByTagName(type.getRecordName());
				    ArrayList<ModelData> records = new ArrayList<ModelData>();
				    for (int i = 0; i < list.getLength(); i++) {
				      Node node = list.item(i);
				      Element elem = (Element) node;
				      ModelData model = newModelInstance();
				      for (int j = 0; j < type.getFieldCount(); j++) {
				        DataField field = type.getField(j);
				        String map = field.getMap() != null ? field.getMap() : field.getName();
				        String v = getValue(elem, map);
				        model.set(field.getName(), v);
				      }
				      records.add(model);
				    }

				    int totalCount = records.size();

				    Node root = doc.getElementsByTagName(type.getRoot()).item(0);
				    if (root != null && type.getTotalName() != null) {
				      Node totalNode = root.getAttributes().getNamedItem(type.getTotalName());
				      if (totalNode != null) {
				        String sTot = totalNode.getNodeValue();
				        totalCount = Integer.parseInt(sTot);
				      }
				    }
				    //获得自曾字段的值
				 
		/*		    if (root != null ) {
					      Node totalNode = root.getAttributes().getNamedItem("autoinc");
					      if (totalNode != null) {
					         autoinc = totalNode.getNodeValue();
					         System.out.println("----------z "+autoinc);
					       }
					    }*/
				    ListLoadResult result = newLoadResult(loadConfig, records);
				    if (result instanceof PagingLoadResult) {
				      PagingLoadResult r = (PagingLoadResult) result;
				      r.setTotalLength(totalCount);
				    }
				    return result;
				  }
					
			
		};
 BasePagingLoader<  PagingLoadResult<JDBCModelData>>  loader = new BasePagingLoader<  PagingLoadResult<JDBCModelData>> (proxy,reader);  

		return loader;
	}
/*	private void getStore()
	{
		
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");

		type.addField("icode");
		type.addField("taskname");
		type.addField("bcode");
		type.addField("predate");
		type.addField("modifydatebak");
		StoreInfo info = new StoreInfo();

		info.setTablename("task");
		info.setSql("select * from task");
//	/	info.setParent(store);// 关联主表
//		info.setAutoinccolumn("idx"); // 自增字段，如果子表一定需要
	//	info.setLinkparentcolumns(new String[] { "ccode" }); // 关联主表字段
	 store = new BaseStore<JDBCModelData> (type, info)
		{
			@SuppressWarnings({ "unchecked", "unchecked" })
			public  BasePagingLoader< PagingLoadResult<JDBCModelData>> getBaseLoader(ModelType type,StoreInfo storeinfo) {
				Date date = new Date();
				RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,
						URL.encode("TaskServlet?Action=Loaddata"));
				builder.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");  
				System.out.println("-0--");
				builder.setCallback(new RequestCallback(){

					@Override
					public void onError(Request request, Throwable exception) {
						// TODO Auto-generated method stub
						System.out.println("error.....");
					}

					@Override
					public void onResponseReceived(Request request, Response response) {
						// 
						
					
					}});
				HttpProxy proxy = new HttpProxy(builder);

				// need a loader, proxy, and reader
				XmlReader reader = new XmlReader(getType())
				{
					
					protected ListLoadResult newLoadResult(Object loadConfig, List models) { 
							PagingLoadConfig pagingConfig = (PagingLoadConfig) loadConfig; 
							PagingLoadResult <ModelData> result = new BasePagingLoadResult<ModelData>(models, 
							pagingConfig.getOffset(), pagingConfig.getLimit()); 
							 
							return result; 
							} 
					@Override 
					 public ListLoadResult read(Object loadConfig, Object data) {
						    Document doc = XMLParser.parse((String) data);

						    NodeList list = doc.getElementsByTagName(getType().getRecordName());
						    ArrayList<ModelData> records = new ArrayList<ModelData>();
						    for (int i = 0; i < list.getLength(); i++) {
						      Node node = list.item(i);
						      Element elem = (Element) node;
						      ModelData model = newModelInstance();
						      for (int j = 0; j < getType().getFieldCount(); j++) {
						        DataField field = getType().getField(j);
						        String map = field.getMap() != null ? field.getMap() : field.getName();
						        String v = getValue(elem, map);
						        model.set(field.getName(), v);
						      }
						      records.add(model);
						    }

						    int totalCount = records.size();

						    Node root = doc.getElementsByTagName(getType().getRoot()).item(0);
						    if (root != null && getType().getTotalName() != null) {
						      Node totalNode = root.getAttributes().getNamedItem(getType().getTotalName());
						      if (totalNode != null) {
						        String sTot = totalNode.getNodeValue();
						        totalCount = Integer.parseInt(sTot);
						      }
						    }
						    //获得自曾字段的值
						 
						    if (root != null ) {
							      Node totalNode = root.getAttributes().getNamedItem("autoinc");
							      if (totalNode != null) {
							         autoinc = totalNode.getNodeValue();
							         System.out.println("----------z "+autoinc);
							       }
							    }
						    ListLoadResult result = newLoadResult(loadConfig, records);
						    if (result instanceof PagingLoadResult) {
						      PagingLoadResult r = (PagingLoadResult) result;
						      r.setTotalLength(totalCount);
						    }
						    return result;
						  }
							
					
				};
		 BasePagingLoader<  PagingLoadResult<JDBCModelData>>  loader = new BasePagingLoader<  PagingLoadResult<JDBCModelData>> (proxy,reader);  

				return loader;
			}
		};
		
	
		
	}*/
	VerticalPanel CreateLeftPanel()
	{
		VerticalPanel vp = new VerticalPanel();
		vp.setWidth(250);
		vp.setAutoHeight(true);
		ContentPanel TaskActionpanel = new ContentPanel();
	
//		TaskActionpanel.setAutoWidth(true);
		TaskActionpanel.setWidth(150);
		TaskActionpanel.setFrame(true);
		TaskActionpanel.setAnimCollapse(true);
		TaskActionpanel.setCollapsible(true);
		TaskActionpanel.setHeading("动作");
		
		ContentPanel viewActionpanel = new ContentPanel();
		
//		TaskActionpanel.setAutoWidth(true);
		viewActionpanel.setWidth(150);
		viewActionpanel.setFrame(true);
		viewActionpanel.setAnimCollapse(true);
		viewActionpanel.setCollapsible(true);
		viewActionpanel.setHeading("显示内容");
		
		
		ContentPanel groupActionpanel = new ContentPanel();
		
//		TaskActionpanel.setAutoWidth(true);
		groupActionpanel.setWidth(150);
		groupActionpanel.setFrame(true);
		groupActionpanel.setAnimCollapse(true);
		groupActionpanel.setCollapsible(true);
		groupActionpanel.setHeading("分组方式");
		
	ContentPanel editablepanel = new ContentPanel();
		
//		TaskActionpanel.setAutoWidth(true);
	editablepanel.setWidth(150);
	editablepanel.setFrame(true);
	editablepanel.setAnimCollapse(true);
	editablepanel.setCollapsible(true);
	editablepanel.setHeading("编辑/浏览方式");
//		Hyperlink b =new Hyperlink();
//		b.setText("ddd");
//		Image b = new Image ("../images/baseimage/icon-show-active.gif");
		Button add = new Button("添加");
		
		add.setWidth(100);
		add.setIconStyle("icon-edit");
		Button havedone = new Button("标记为已完成");
		havedone.setWidth(100);
		havedone.setIconStyle("icon-complete");
		Button nodone = new Button("标记为未完成");
		nodone.setWidth(100);
		nodone.setIconStyle("icon-active");
		Button delete = new Button("删除");
		delete.setWidth(100);
		delete.setIconStyle("icon-delete");
		TaskActionpanel.add(add);
		TaskActionpanel.add(havedone);
		TaskActionpanel.add(nodone);
		TaskActionpanel.add(delete);
		
		
		havedone.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				//System.out.println("--"+groupgrid.getSelectionModel().getSelectedItem().get("status"));
				//groupgrid.getSelectionModel().getSelectedItem().set("status", "2");
				int index = groupgrid.getStore().indexOf(groupgrid.getSelectionModel().getSelectedItem());
				if(index>=0)
				{groupgrid.getStore().getAt(index).set("status", "2");
					
				
				formBindings.bind(groupgrid.getSelectionModel().getSelectedItem());
				leftformBindings.bind(groupgrid.getSelectionModel().getSelectedItem());
				rightformBindings.bind(groupgrid.getSelectionModel().getSelectedItem());
				}
				groupgrid.getView().refresh(true);
			}
			
		});
		
		
		Button alltask = new Button("所有任务");
		
		alltask.setWidth(100);
		alltask.setIconStyle("icon-show-all");
		Button doing = new Button("正在处理");
		doing.setWidth(100);
		doing.setIconStyle("icon-show-active");
		Button havedonetask = new Button("已完成任务");
		havedonetask.setWidth(100);
		havedonetask.setIconStyle("icon-show-complete");
		viewActionpanel.add(alltask);
		viewActionpanel.add(doing);
		viewActionpanel.add(havedonetask);

		
		
		Button time = new Button("时间");
		
		time.setWidth(100);
		time.setIconStyle("icon-by-date");
		Button addr = new Button("人员");
		addr.setWidth(100);
		addr.setIconStyle("icon-by-category");
		Button status = new Button("完成？");
		status.setWidth(100);
		status.setIconStyle("icon-by-category");
		Button none = new Button("什么都没有");
		none.setWidth(100);
		none.setIconStyle("icon-no-group");
		time.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				 groupstore.groupBy("modifydatebak");  
			}
			
		});
		
		addr.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				 groupstore.groupBy("bcode");  
			}
			
		});
		
		status.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				 groupstore.groupBy("status");  
			}
			
		});
		
		none.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				 groupstore.clearGrouping(); 
			
			}
			
		});
		
		
		
		groupActionpanel.add(time);
		groupActionpanel.add(addr);
		groupActionpanel.add(status);
		groupActionpanel.add(none);

		final CheckBox checkbox = new CheckBox();
		
		checkbox.addListener(Events.OnClick ,new Listener<FieldEvent>(){

			@Override
			public void handleEvent(FieldEvent be) {
				// TODO Auto-generated method stub
				System.out.println("dd"+checkbox.getValue());
				if(checkbox.getValue())
				{
					checkbox.setBoxLabel("编辑模式");
					groupgrid.getSelectionModel().deselectAll();
				}
				else
				{
					checkbox.setBoxLabel("浏览模式");
			
				}
			}
			
		});
		checkbox.setBoxLabel("浏览模式");
		editablepanel.add(checkbox);
		
		vp.add(TaskActionpanel);
		
		vp.add(viewActionpanel);
		
		vp.add(groupActionpanel);
		vp.add(editablepanel);
		return vp;
	}
	
	@SuppressWarnings("unchecked")
	Grid getGroupGrid()
	{
	CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());
		ColumnConfig subject = new ColumnConfig("subject", "任务主题", 200);
//		TextField<String> tasknametext = new TextField<String>();
//		taskname.setEditor(new CellEditor(tasknametext));
		columns.add(subject);
		
		ColumnConfig bcode = new ColumnConfig("bcode", "人员", 100);
//		TextField<String> bcodetext = new TextField<String>();
//		bcode.setEditor(new CellEditor(bcodetext));
		columns.add(bcode);
		
		
		ColumnConfig predate = new ColumnConfig("predate", "录入时间", 100);
//		TextField<String> predatetext = new TextField<String>();
//		predate.setEditor(new CellEditor(predatetext));
		columns.add(predate);
		
		ColumnConfig modifydatebak = new ColumnConfig("modifydatebak", "最后修改时间", 100);
//		TextField<String> modifydatebaktext = new TextField<String>();
//		modifydatebak.setEditor(new CellEditor(modifydatebaktext));
		columns.add(modifydatebak);
		ColumnConfig status = new ColumnConfig("status", "标识", 100);
//		TextField<String> modifydatebaktext = new TextField<String>();
//		modifydatebak.setEditor(new CellEditor(modifydatebaktext));
	
		
	GridCellRenderer<ModelData>	renderer = new GridCellRenderer<ModelData>() {

      public String render(ModelData model, String property, ColumnData d, int rowIndex,
          int colIndex, ListStore<ModelData> store, Grid<ModelData> grid) {
      
       if(model.get(property).equals("1"))
        return "" + ("<img src='../images/baseimage/icon-active.gif' />" );
       else if(model.get(property).equals("2"))
    	   return "" + ("<img src='../images/baseimage/icon-complete.gif' />" );
       return "" + ("<img src='../images/baseimage/icon-active.gif' />" );
      }
    };
	status.setRenderer(renderer);
		columns.add(status);
		
		 CheckColumnConfig checkColumn = new CheckColumnConfig("icode", "bcode?", 55) {
		      protected String getCheckState(ModelData model, String property, int rowIndex,
		          int colIndex) {
		    
		        return "-disabled";
		      }
		    };
		  
		final ColumnModel cm = new ColumnModel(columns);

	    GroupingView view = new GroupingView();  
	    view.setShowGroupedColumn(false);  
	    view.setForceFit(true);  
	    view.setGroupRenderer(new GridGroupRenderer() {  
	      public String render(GroupColumnData data) {  
	        String f = cm.getColumnById(data.field).getHeader();  
	        String l = data.models.size() == 1 ? "Item" : "Items";  
	        return f + ": " + data.group + " (" + data.models.size() + " " + l + ")";  
	      }  
	    });  
	    
	    Grid grid = new Grid(groupstore, cm);  
	    grid.setView(view);  
	    grid.setBorders(true);  
	    grid.setHeight(400); 
	    grid.setWidth(800);
	//	grid.setAutoWidth(true);
		grid.getSelectionModel().setSelectionMode(SelectionMode.MULTI);  
		 grid.getSelectionModel().addListener(Events.SelectionChange,
				new Listener<SelectionChangedEvent>() {
					@Override
					public void handleEvent(SelectionChangedEvent be) {
						if (be.getSelection().size() > 0) {
						
							formBindings.bind((ModelData) be.getSelection()
									.get(0));
							leftformBindings.bind((ModelData) be.getSelection()
									.get(0));
							rightformBindings.bind((ModelData) be.getSelection()
									.get(0));
						} else {
							formBindings.unbind();
							leftformBindings.unbind();
							rightformBindings.unbind();
						}
					}

					
		
			        });  
		 
	    return grid;
	}
/*	@SuppressWarnings("unchecked")
	BaseGrid getBaseGrid()
	{
		
		
		type.addField("icode");
		type.addField("taskname");
		type.addField("bcode");
		type.addField("predate");
		type.addField("modifydatebak");
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());
		ColumnConfig taskname = new ColumnConfig("taskname", "任务", 200);
//		TextField<String> tasknametext = new TextField<String>();
//		taskname.setEditor(new CellEditor(tasknametext));
		columns.add(taskname);
		
		ColumnConfig bcode = new ColumnConfig("bcode", "人员", 100);
//		TextField<String> bcodetext = new TextField<String>();
//		bcode.setEditor(new CellEditor(bcodetext));
		columns.add(bcode);
		
		
		ColumnConfig predate = new ColumnConfig("predate", "录入时间", 100);
//		TextField<String> predatetext = new TextField<String>();
//		predate.setEditor(new CellEditor(predatetext));
		columns.add(predate);
		
		ColumnConfig modifydatebak = new ColumnConfig("modifydatebak", "最后修改时间", 100);
//		TextField<String> modifydatebaktext = new TextField<String>();
//		modifydatebak.setEditor(new CellEditor(modifydatebaktext));
		columns.add(modifydatebak);
		
		 CheckColumnConfig checkColumn = new CheckColumnConfig("icode", "bcode?", 55) {
		      protected String getCheckState(ModelData model, String property, int rowIndex,
		          int colIndex) {
		    
		        return "-disabled";
		      }
		    };
		  
		ColumnModel cm = new ColumnModel(columns);
		
		BaseGrid grid = new BaseGrid(store, cm);
		
		cbs.setSelectionMode(SelectionMode.MULTI);

		grid.setSelectionModel(cbs);
		
		grid.addPlugin(checkColumn);
	//	store.load();
		grid.setHeight(300);
		grid.setAutoWidth(true);
		grid.setShim(true);
		grid.setLoadMask(false);
		//grid.setEnabled(false);
		
		return grid;
	}*/
	
	FieldSet CreateForm()
	{
		
		 toppanel = new FormPanel();
	
		
		toppanel.setHeaderVisible(false);
		toppanel.setBodyBorder(false);
		
		 leftpanel = new FormPanel();

		leftpanel.setHeaderVisible(false);
		leftpanel.setBodyBorder(false);
		
		FormData fd = new FormData(500, 100);

		 rightpanel = new FormPanel();
		rightpanel.setBodyBorder(false);
		rightpanel.setHeaderVisible(false);
		
		
		final TextArea subject = new TextArea();
		subject.setMaxLength(200);
		
		subject.setName("subject");
		subject.setAllowBlank(false);
		subject.setFieldLabel("任务主题");
		final TextArea taskname = new TextArea();
		taskname.setMaxLength(200);
		
		taskname.setName("taskname");
		taskname.setAllowBlank(false);
		taskname.setFieldLabel("任务");
		final TextArea fromaddr = new TextArea();
		fromaddr.setMaxLength(200);
		
		fromaddr.setName("fromaddr");
		fromaddr.setAllowBlank(false);
		fromaddr.setFieldLabel("发货地址");
		final TextArea toaddr = new TextArea();
		toaddr.setMaxLength(200);
		
		toaddr.setName("toaddr");
		toaddr.setAllowBlank(false);
		toaddr.setFieldLabel("收货地址");
		
		
		final TextField<String> icode = new TextField<String>();
		icode.setName("icode");
		icode.setAllowBlank(false);
		icode.setFieldLabel("编码");
		icode.setEnabled(false);
		
		
		final TextField<String> bcode = new TextField<String>();
		bcode.setName("bcode");
		bcode.setAllowBlank(false);
		bcode.setFieldLabel("人员");
		bcode.setEnabled(false);
		
		final TextField<String> status = new TextField<String>();
		status.setName("status");
		status.setAllowBlank(false);
		status.setFieldLabel("标识");
		status.setEnabled(false);
		
		toppanel.add(taskname,fd);
		leftpanel.add(subject);
		
		
		rightpanel.add(fromaddr);
		leftpanel.add(toaddr);
		rightpanel.add(bcode);
		leftpanel.add(icode);
		rightpanel.add(status);
		LayoutContainer main = new LayoutContainer();
		TableLayout tl = new TableLayout(2);

		
		
		FieldSet fieldSet = new FieldSet();
		fieldSet.setLayout(tl);
		TableData td = new TableData();
		td.setColspan(1);
		td.setRowspan(1);
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.TOP);
		TableData td2 = new TableData();
		td2.setColspan(2);
		td2.setRowspan(1);
		
		fieldSet.add(toppanel,td2);
		fieldSet.add(leftpanel,td);
		fieldSet.add(rightpanel,td);
		
//		toppanel.inited();
//		leftpanel.inited();
//		rightpanel.inited();
		fieldSet.setAutoWidth(true);
		fieldSet.setAutoHeight(true);
		fieldSet.setHeading("任务...");
		
		
		LayoutContainer layoutcontainer = new LayoutContainer();
		layoutcontainer.setLayout(new ColumnLayout());
		

		Button newtask = new Button("添加新任务");
		Button save = new Button("保存");
		Button delete = new Button("删除");
		newtask.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
			
				//grid.addnewrecord();
				groupgrid.getSelectionModel().deselectAll();
			}
			
		});
		save.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				SendServlet sendservlet = new SendServlet();
				
				String p = "&taskname="+taskname.getValue()+"&bcode="+bcode.getValue()+"&icode="+icode.getValue()+"&subject="+subject.getValue()+"&fromaddr="+fromaddr.getValue()+"&toaddr="+toaddr.getValue()+"&status="+status.getValue();
				try {
					sendservlet.sendServlet("TaskServlet", "Action=save"+p, new RequestCallback(){

						@Override
						public void onError(Request request, Throwable exception) {
							// TODO Auto-generated method stub
							
						}

						@Override
						public void onResponseReceived(Request request,
								Response response) {
						
							if(response.getText().indexOf(Env.SUCCESS)>=0)
							{
								
								//toppanel.getFormbinding().unbind();
								groupgrid.getSelectionModel().deselectAll();
								//taskname.setValue("");
							}
								
						}
					});
				} catch (RequestException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		});
		
		delete.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
		
				
			}
			
		});
		
		
		layoutcontainer.add(newtask);
		layoutcontainer.add(save);
		layoutcontainer.add(delete);
		
		fieldSet.add(layoutcontainer);
	
		return fieldSet;
	}
	
	@SuppressWarnings("unchecked")
	private Map<String, List> listeners;
	@SuppressWarnings("unchecked")
	public void addHeardBeatListener(String eventType, HeardBeatListener listener) {
		if (listener == null)
			return;
		if (listeners == null) {
			listeners = new HashMap<String, List>();
		}
		List<HeardBeatListener> list = listeners.get(eventType);
		if (list == null) {
			list = new ArrayList<HeardBeatListener>();
			listeners.put(eventType, list);
		}

		if (!list.contains(listener)) {
			list.add(listener);
		}

	}

	public void removeHeardBeatListener(final int eventType,
			final Listener listener) {
		if (listeners == null) {
			return;
		}

		List<Listener> list = listeners.get(eventType);
		if (list != null) {
			list.remove(listener);
			if (list.isEmpty()) {
				listeners.remove(eventType);
			}
		}

	}

	@Override
	public void HeardBeatEventHandle(HeardBeatEvent evt) {
		// TODO Auto-generated method stub
		isneedreload = true;
		if(!isediting)
		{
		//store.reload();
		loder.load();
		}
	}


}
